/*
 * Copyright 2013-2015 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.xdtech.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 
 * @author max.zheng
 * @create 2015-8-27下午10:31:59
 * @since 1.0
 * @see
 */
public class UDPSender {
	public static void main(String[] args) throws Exception {
		String msg = "Hello, World";
		byte[] buf = msg.getBytes();
		try {
			InetAddress address = InetAddress.getByName("169.254.139.161"); // 服务器地址
			int port = 8999; // 服务器的端口号
			// 创建发送方的数据报信息
			DatagramPacket dataGramPacket = new DatagramPacket(buf, buf.length,
					address, port);

			DatagramSocket socket = new DatagramSocket(); // 创建套接字
			socket.send(dataGramPacket); // 通过套接字发送数据

			Thread.sleep(30000);
			// 接收服务器反馈数据
			byte[] backbuf = new byte[1024];
			DatagramPacket backPacket = new DatagramPacket(backbuf,
					backbuf.length);
			socket.receive(backPacket); // 接收返回数据
			String backMsg = new String(backbuf, 0, backPacket.getLength());
			System.out.println("服务器返回的数据为:" + backMsg);

			socket.close();

		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
